<template>
  <common-list-group class="report-component-wrap">
    <!-- 组件配置 -->
    <config
      v-if="isConfigDialog"
      :type="searchForm.id"
      :classType="searchForm.classType"
      :typeName="typeName"
      :id="componentId"
      :departmentList="departmentList"
      @close="closeConfig"
    ></config>

    <preview
      v-if="isPreviewDialog"
      :id="componentId"
      :chartType="chartType"
      :title="componentName"
      @close="closePreview"
    ></preview>

    <div
      slot="group"
      class="group-list-component-wrap"
      v-loading="isGroupLoading"
    >
      <div class="group-header-wrap">
        <div class="group-header-title">组件分类</div>
      </div>
      <common-tree
        ref="treeRef"
        :is-slot="true"
        :tree-data="typeList"
        :isRequest="isRequest"
        :hiddenIndexIcon="3"
        :tree-prop="{ isLeaf: 'leaf' }"
        :current-node-key="currentNodeId"
        @handleNodeClick="groupClick"
        search-placeholder="查询组件分类"
        is-show-icon-for-no-child
        set-node-by-key="leaf"
      >
        <div slot-scope="{ scope }" class="tree-item-wrap">
          <common-carousel-text :content="scope.data.name" :font-size="14" />
          <el-popover
            v-if="scope.data.isDefault === 0"
            popper-class="chart-type-list-popover"
            placement="right-start"
            width="150"
            trigger="hover"
          >
            <!--            <i slot="reference" class="iconfont icon-more"></i>-->
            <commonIcon
              slot="reference"
              iconName="icon-more"
              iconType="icon"
              :iconSize="16"
            ></commonIcon>
            <common-menu>
              <common-menu-item
                v-if="scope.node.level < 3"
                @click="handleTypeAddDialog(scope.data)"
                v-hasPermi="['system:reportparts:addNode']"
                >新增子分类
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                @click="handleTypeEditDialog(scope.data)"
                v-hasPermi="['system:reportparts:editNode']"
                >编辑
              </common-menu-item>
              <common-menu-item
                v-if="!scope.data.isRoot"
                @click="handleDeleteTree(scope.data.id)"
                v-hasPermi="['system:reportparts:delNode']"
                >删除
              </common-menu-item>
            </common-menu>
          </el-popover>
        </div>
      </common-tree>
    </div>

    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        ref="queryForm"
        :inline="true"
        label-width="80px"
        :model="searchForm"
        @submit.native.prevent
      >
        <el-form-item label="数据集名称" prop="datasetName">
          <common-input v-model="searchForm.datasetName" @enter="handleQuery">
          </common-input>
        </el-form-item>
        <el-form-item label="组件名称" prop="name">
          <common-input v-model="searchForm.name" @enter="handleQuery">
          </common-input>
        </el-form-item>
        <el-form-item label="图表类型" prop="chartType">
          <el-select v-model="searchForm.chartType">
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="chart in chartList"
              :label="chart.getInfo().name"
              :value="chart.getInfo().type"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>
    <div slot="tools">
      <el-row :gutter="10" v-if="!predefined">
        <el-col :span="1.5">
          <el-button
            type="primary"
            :disabled="hasType"
            plain
            icon="el-icon-plus"
            @click="handleAdd"
            v-hasPermi="['system:reportparts:addSubgroup']"
            >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :disabled="!showBatch"
            icon="el-icon-delete"
            @click="handleDelete()"
            v-hasPermi="['system:reportparts:delSubgroup']"
            >批量删除
          </el-button>
        </el-col>
      </el-row>
    </div>
    <common-table
      slot="content"
      v-loading="loading"
      @selection-change="handleSelectionChange"
      :data="List"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="组件名称"
        align="left"
        prop="name"
        fixed
        show-tooltip-when-overflow
      />
      <el-table-column
        label="数据集"
        align="left"
        prop="dataset.name"
        show-tooltip-when-overflow
      />
      <el-table-column
        label="图表类型"
        align="left"
        prop="chartTypeName"
        show-tooltip-when-overflow
      />
      <el-table-column
        label="所属分类"
        align="left"
        prop="typeName"
        show-tooltip-when-overflow
      />
      <el-table-column
        label="关联组件"
        align="left"
        prop="relationComponentName"
        show-tooltip-when-overflow
      />
      <el-table-column
        label="创建时间"
        align="left"
        prop="createTime"
        width="170px"
      />
      <el-table-column
        label="操作"
        align="left"
        prop="operation"
        width="160px"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button type="text" @click="handlePreview(scope.row)"
            >预览
          </el-button>
          <el-button
            v-if="!predefined"
            type="text"
            @click="handleEditGroup(scope.row)"
            v-hasPermi="['system:reportparts:editTypeSubgroup']"
            >分类
          </el-button>
          <el-button
            v-if="($route.query.super_dev === 'true' && isAdmin) || !predefined"
            type="text"
            @click="handleEdit(scope.row)"
            v-hasPermi="['system:reportparts:editSubgroup']"
            >编辑
          </el-button>
          <el-button
            v-if="!predefined"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:reportparts:delSubgroup']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="searchForm.pageNum"
      :limit.sync="searchForm.pageSize"
      @pagination="getList"
    />

    <common-edit-dialog
      :title="`${isTypeEdit ? '编辑' : '新增'}分类`"
      width="25%"
      :visible="isTypeDialog"
      :button-loading="typeButtonLoading"
      @cancel="typeDialogCancel"
      @submit="persistenceTypeForm"
    >
      <el-form
        ref="typeForm"
        :model="typeForm"
        :rules="typeRule"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <common-input
            style="width: 100%"
            :maxlength="16"
            v-model="typeForm.name"
          ></common-input>
        </el-form-item>
        <!-- <common-add-dept
          ref="commonAddDept"
          :deptListParams="departmentList"
          @getCheckedDeptId="getCheckedDeptId"
          :deptId="typeForm.deptId"
        ></common-add-dept> -->
      </el-form>
    </common-edit-dialog>

    <common-edit-dialog
      title="切换分类"
      :visible="isEditGroupDialog"
      @cancel="componentDialogCancel"
      width="25%"
      @submit="persistenceComponentForm"
      :button-loading="typeChangeButtonLoading"
    >
      <el-form
        ref="componentForm"
        :model="componentForm"
        :rules="componentRule"
        label-width="60px"
        @submit.native.prevent
      >
        <el-form-item label="分类" style="margin-bottom: 0">
          <el-cascader
            style="width: 100%"
            v-model="componentForm.type"
            :options="groupList"
            :props="cascaderProps"
            :show-all-levels="false"
          >
            <template slot-scope="{ node, data }">
              <common-marquee-text :content="data.name"></common-marquee-text>
            </template>
          </el-cascader>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
  </common-list-group>
</template>

<script>
import BaseList from "@/mixins/BaseList";
import config from "./config";
import preview from "./preview";
import {
  addType,
  editType,
  removeType,
  deleteCheckType,
  queryType,
  queryPageList,
  deleteComponent,
  editComponentType,
  deleteForCheck,
} from "@/api/screenConfig/dataComponents";
import { ChartList } from "./configuration";
import { deleteSubChildren } from "@/utils";
import { getSingleArray, getFullDept } from "@/utils/util";
import { mapGetters } from "vuex";
import commonIcon from "@/components/CommonIcon";

export default {
  name: "index",
  components: {
    config,
    preview,
    commonIcon,
  },
  mixins: [BaseList],
  data() {
    return {
      isRequest: false,
      typeChangeButtonLoading: false,
      typeButtonLoading: false,
      isGroupLoading: false,
      isConfigDialog: false,
      isPreviewDialog: false,
      isDialog: false,
      predefined: false,
      isEditGroupDialog: false, //
      buttonLoading: false,
      // 遮罩层
      loading: false,
      isTypeDialog: false,
      isTypeEdit: false,
      typeProps: {
        label: "name",
      },
      total: 0,

      chartList: ChartList,
      typeName: "",
      currentNodeId: "",
      searchForm: {
        name: "",
        datasetName: "",
        chartType: null,
        id: "",
        isDefault: 0,
        classType: 0,
        pageNum: 1,
        pageSize: 10,
        deptIds: null,
      },
      typeForm: {
        id: null,
        name: "",
        classType: 0,
        parentId: 0,
        deptId: null,
      },
      typeRule: {
        name: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        // deptId: [{ required: true, message: '请选择组织', trigger: 'blur' }]
      },
      componentForm: {
        id: "",
        type: "",
      },
      componentRule: {
        type: [{ required: true, message: "请选择分类", trigger: "blur" }],
      },
      typeList: [
        {
          id: "0-1",
          key: "0",
          isDefault: 1,
          classType: 0,
          leaf: false,
          isRoot: true,
          name: "预定义",
          sort: 1,
          children: [],
        },
        {
          id: "0-2",
          key: "0",
          isDefault: 0,
          classType: 0,
          leaf: false,
          isRoot: true,
          name: "自定义",
          sort: 2,
          children: [],
        },
        {
          id: "0-3",
          key: "0",
          isDefault: 0,
          classType: 1,
          leaf: false,
          isRoot: true,
          name: "审计分类",
          sort: 2,
          children: [],
        },
      ],
      List: [],

      componentId: "",
      componentName: "",
      cascaderProps: {
        label: "name",
        value: "key",
        checkStrictly: true,
        emitPath: false,
      },
      currentParent: 1,
      singleDeptList: [],
      departmentList: [],
      chartType: null,
    };
  },
  computed: {
    ...mapGetters(["isAdmin"]),
    hasType: function () {
      return (this.searchForm.id ?? "") === "";
    },
    groupList: function () {
      // classType 0 自定义  1 审计分类
      // typeList 0 预定义 1 自定义 2 审计分类
      return deleteSubChildren([this.typeList[this.searchForm.classType + 1]]);
    },
  },
  methods: {
    // getCheckedDeptId(val) {
    //   this.typeForm.deptId = val;
    // },
    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },

    /**
     * 获取分类列表
     */
    getGroupData() {
      const handleKey = (array) => {
        return array.map((item) => {
          item.key = item.id;
          if (
            item.children &&
            item.children instanceof Array &&
            item.children.length
          ) {
            item.children = handleKey(item.children);
          }
          return item;
        });
      };

      this.isGroupLoading = true;
      queryType({})
        .then((res) => {
          if (res && res.code === 200) {
            let list = handleKey(res.data);

            // isDefault 0是自定义 1是预定义
            // classType 0是报表类型 1是审计类型

            let report = list.filter((item) => item.classType !== 1);
            let audit = list.filter((item) => item.classType === 1);

            this.typeList[0].children = report.filter(
              (item) => item.isDefault === 1
            );
            this.typeList[1].children = report.filter(
              (item) => item.isDefault === 0
            );
            this.typeList[2].children = audit;

            this.typeName = "自定义";
            this.$nextTick(() => {
              this.groupChange(this.typeList[1]);
            });
          } else {
            this.typeList = [];
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.isGroupLoading = false;
        });
    },
    /**
     * 处理分类新增弹框
     * @param data
     */
    handleTypeAddDialog(data) {
      this.typeForm.name = "";
      this.typeForm.remark = "";
      this.typeForm.classType = data.classType;
      this.typeForm.parentId = data.key;
      this.isTypeDialog = true;
      this.isTypeEdit = false;
    },
    /**
     * 处理分类编辑弹框
     * @param data
     */
    handleTypeEditDialog(data) {
      this.typeForm.id = data.key;
      this.typeForm.name = data.name;
      this.typeForm.remark = data.remark;
      this.typeForm.classType = data.classType;
      this.typeForm.parentId = data.parentId;
      this.typeForm.deptId = data.deptId;
      this.isTypeDialog = true;
      this.isTypeEdit = true;
    },
    /**
     * 分类删除
     * @param data
     */
    deleteTreeData(id) {
      this.$GlobalDeleteConfirm()
        .then(() => {
          removeType({ ids: id })
            .then((res) => {
              this.$GlobalSuccessMessage("删除成功");
            })
            .finally(() => {
              this.getGroupData();
            });
        })
        .catch(() => {});
    },

    /**
     * 左侧树形通用删除前校验方法
     */
    beforeDeleteTreeForCheck(id) {
      return new Promise((resolve, reject) => {
        deleteCheckType({ ids: id }).then((res) => {
          if (res && res.code === 200) {
            resolve(res);
          } else {
            reject(res);
          }
        });
      });
    },

    /**
     * 分类点击事件
     * @param node
     * @param data
     */
    groupClick({ node, data }) {
      this.groupChange(data);
    },
    /**
     * 分类改变事件
     * @param data
     */
    groupChange(data) {
      console.log("当前选择的分类: ", data);
      this.currentNodeId = data.id;
      this.typeName = data.name;
      this.classType = data.classType;
      this.searchForm.id = data.key;
      this.searchForm.isDefault = data.isDefault;
      this.searchForm.classType = data.classType;
      this.predefined = data.isDefault === 1;

      this.handleQuery();
    },
    // 搜索查询
    handleQuery() {
      this.searchForm.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    resetQuery() {
      this.$refs.queryForm.resetFields();
    },
    /**
     * 报表组件列表接口
     */
    getList() {
      this.loading = true;
      this.isRequest = true;
      queryPageList({
        ...this.searchForm,
        "dataset.name": this.searchForm.datasetName,
      })
        .then((res) => {
          if (res && res.code === 200) {
            this.total = res.total;
            this.List = res.rows.reduce((r, c) => {
              let chart = this.chartList.find(
                (chart) => chart.getInfo().type === c.chartType
              );
              r.push({
                ...c,
                chartTypeName: chart ? chart.getInfo().name : c.chartType,
                deptName: this.getDeptName(c.deptId || ""),
              });
              return r;
            }, []);
          } else {
            this.List = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
          this.isRequest = false;
        });
    },

    // 报表 配置页面 打开
    handleAdd() {
      this.componentId = null;
      this.isConfigDialog = true;
    },
    // 编辑
    handleEdit(row) {
      console.log("编辑的组件信息: ", row);
      this.componentId = row.id;
      this.isConfigDialog = true;
    },
    handleEditGroup(row) {
      console.log("type: ", row.type);
      this.componentForm.id = row.id;
      this.componentForm.type = row.type;
      this.isEditGroupDialog = true;
    },
    // 报表 配置页面 关闭
    closeConfig() {
      this.isConfigDialog = false;
      this.getList();
    },
    // 报表组件删除
    deleteData(row) {
      const ids = row?.id || this.ids.join(",");
      this.$GlobalDeleteConfirm()
        .then(() => {
          deleteComponent({ ids }).then((res) => {
            if (res && res.code === 200) {
              this.$GlobalSuccessMessage("删除成功");
              if (
                this.searchForm.pageNum > 1 &&
                ids.split(",").length === this.List.length
              ) {
                this.searchForm.pageNum -= 1;
              }
              this.getList();
            } else {
              this.$GlobalErrorConfirm("删除失败", res.msg);
            }
          });
        })
        .catch(() => {});
    },
    /**  删除前校验 */
    beforeDeleteForCheck(ids) {
      return new Promise((resolve, reject) => {
        deleteForCheck({ ids: ids })
          .then((res) => {
            if (res && res.code === 200) {
              resolve(res);
            } else {
              reject(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    typeDialogCancel() {
      this.isTypeDialog = false;
    },
    persistenceTypeForm() {
      this.$refs.typeForm.validate((valid) => {
        if (valid) {
          this.typeButtonLoading = true;
          if (this.isTypeEdit) {
            editType(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("编辑成功");
                } else {
                  this.$GlobalErrorConfirm("编辑失败", res.msg);
                }
              })
              .finally(() => {
                this.typeForm.deptId = null;
                this.getGroupData();
                this.isTypeDialog = false;
                this.typeButtonLoading = false;
              });
          } else {
            addType(this.typeForm)
              .then((res) => {
                if (res && res.code === 200) {
                  this.$GlobalSuccessMessage("新增成功");
                } else {
                  this.$GlobalErrorConfirm("新增失败", res.msg);
                }
              })
              .finally(() => {
                this.typeForm.deptId = null;
                this.getGroupData();
                this.isTypeDialog = false;
                this.typeButtonLoading = false;
              });
          }
        }
      });
    },

    persistenceComponentForm() {
      this.$refs.componentForm.validate((valid) => {
        if (valid) {
          this.typeChangeButtonLoading = true;
          editComponentType(this.componentForm)
            .then((res) => {
              if (res && res.code === 200) {
                this.$GlobalSuccessMessage("修改分类成功");
              } else {
                this.$GlobalErrorConfirm("切换分类失败", res.msg);
              }
            })
            .finally(() => {
              this.isEditGroupDialog = false;
              this.typeChangeButtonLoading = false;
              this.getList();
            });
        }
      });
    },
    componentDialogCancel() {
      this.isEditGroupDialog = false;
    },
    handlePreview(row) {
      this.componentId = row.id;
      this.componentName = row.name;
      this.chartType = row.chartType;
      this.isPreviewDialog = true;
    },
    closePreview() {
      this.isPreviewDialog = false;
    },
  },
  mounted() {
    this.getGroupData();
  },
};
</script>

<style scoped lang="scss">
.report-component-wrap {
  .tree-item-wrap {
    display: flex;
    align-items: center;
    width: 100%;

    &:hover {
      .iconfont {
        opacity: 1;
      }
    }

    .iconfont {
      opacity: 0;
      transition: opacity 0.15s linear;
    }

    .tree-label {
      margin-right: 4px;
    }

    .pre-icon {
      width: 12px;
      height: 12px;
      font-size: 12px;
    }
  }

  .group-header-wrap {
    height: 32px;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .group-header-title {
      font-size: 14px;
    }
  }
}
</style>
